<template>
    <div>
        <el-row type="flex" style="margin-top:3%" :gutter="20">
            <el-col :span="4">
                <div class="grid-content bg-purple-light"></div>
            </el-col>
            <el-col :span="16">
                <el-form ref="form" :rules="formRules" :model="form" label-width="110px" label-position="left">
                    <el-form-item label="标题" prop="title">
                        <el-col :span="24">
                            <el-input v-model.trim="form.title" placeholder="请输入标题，（建议14字以内，不超过30个字）" minlength="14" maxlength="30">
                                <template slot="append">{{getInputLength(form.title)}}/30
</template>
                        </el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="作者" prop="author">
                    <el-col :span="24">
                        <el-input v-model.trim="form.author"  placeholder="请输入作者，（建议14字以内，不超过30个字）" minlength="14" maxlength="30">
<template slot="append">
    {{getInputLength(form.author)}}/30
</template>
                        </el-input>
                    </el-col>
                </el-form-item>
                 <el-form-item label="译者" prop="translator">
                    <el-col :span="24">
                        <el-input v-model.trim="form.translator"  placeholder="请输入译者，（建议14字以内，不超过30个字）" minlength="14" maxlength="30">
<template slot="append">
    {{getInputLength(form.translator)}}/30
</template>
                        </el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="来源" prop="origin">
                    <el-col :span="24">
                        <el-input v-model.trim="form.origin"  placeholder="请输入来源，（建议14字以内，不超过30个字）" minlength="14" maxlength="30">
<template slot="append">
    {{getInputLength(form.origin)}}/30
</template>
                        </el-input>
                    </el-col>
                </el-form-item>
                <el-form-item  label="内容分类">
                    <el-col :span="12">
                        <el-select multiple clearable v-model="form.contentClassifies" placeholder="请选择" style="width:100%;">
                            <el-option
                            v-for="item in classifies"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item  label="兴趣标签" >
                            <el-form-item prop="tagIds">
                            <el-select  multiple v-model="form.tagIds" placeholder="请选择" style="width:100%;">
                                    <el-option
                                    v-for="item in Tags"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                 <el-form-item label="选择杂志" prop="magazineId">
                    <el-col :span="24">
                        <el-select :disabled="true" v-model="form.magazineId" placeholder="请选择" style="width:100%;">
                            <el-option
                            v-for="item in magazines"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="选择杂志栏目" prop="columnId">
                    <el-col :span="12">
                        <el-select v-model="form.columnId" placeholder="请选择" style="width:100%;">
                            <el-option
                            v-for="item in columns"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="排序" prop="contentNum">
                           <el-input-number v-model="form.contentNum" size="small"  style="width:100%;" controls-position="right"  :min="1" :max="99" ></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="摘要">
                    <el-col :span="22">
                        <el-input type="textarea"  placeholder="请输入摘要，不要超过200字" v-model.trim="form.introduction" :autosize="{ minRows: 4, maxRows: 8 }" minlength="1" maxlength="200" class="m-zc-textarea">
                        </el-input>
                    </el-col>
                    <el-col :span="2">
                        <span style="color:#909399">{{getInputLength(form.introduction)}}/200</span>
                    </el-col>
                </el-form-item>
                <el-form-item label="封面图" prop="cover">
                   <el-col :span="24">
                            <el-upload
                                action="/api/img/upload"
                                id="upload_control"
                                :on-success = "successFile"
                                :before-upload="handleBefore" 
                                :show-file-list="false"
                                style="float:left">
                                 <el-button>选择图片</el-button>
                            </el-upload>
                           <span class="upload_span">建议宽高比：315px*315px</span>
                            <!-- <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="form.cover" alt="">
                            </el-dialog> -->
                            <el-input type="hidden" style="width:0;height:0;" v-model="form.cover"></el-input>
                             
                            <div v-if="form.cover != null" style="margin-top:10px"><img :src="form.cover" height="200px" /></div>
                        </el-col>
                </el-form-item>
                <el-form-item label="编辑内容" prop="content">
                    <el-col :span="24">
                        <tinymce :height="400" ref="tinyme" :id="tinymeId" v-model="form.content"></tinymce>
                    </el-col>
                </el-form-item>
                <el-form-item label="允许试读" prop="trialRead">
                    <el-col :span="24">
                        <el-radio-group v-model="form.trialRead">
                            <el-radio class="radio"  :label="1">是</el-radio>
                            &nbsp;&nbsp;&nbsp;
                            <el-radio class="radio"  :label="0">否</el-radio>
                        </el-radio-group>
                    </el-col>
                </el-form-item>
                <br/>
                <el-form-item>
                    <el-button @click="onSubmit" class="form_button">提交</el-button>
                    <el-button  @click="back" class="form_button">取消</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <el-col :span="7"><div class="grid-content bg-purple-light"></div></el-col>
    </el-row>
    </div>
</template>

<script>
    import {
        uploadImg
    } from '@/api/common/upload'
    import Tinymce from '@/components/Tinymce'
    import　 {
        getAllClassifies
    } from '@/api/sys/classify'
    import {
        getSelectColumnBox
    } from '@/api/magazine/magazinecolumn'
    import {
        getChildTags
    } from '@/api/sys/tag'
    import {
        insertMagazineContent,
        updateMagazineContent,
        getMagazineContentById
    } from '@/api/magazine/magazinecontent'
    
    export default {
        components: {
            Tinymce
        },
        data() {
            return {
                dialogVisible: false,
                tinymeId: 'm_conetent',
                form: {
                    id: undefined,
                    title: undefined,
                    author: undefined,
                    translator: undefined,
                    origin: undefined,
                    contentClassifies: [],
                    tagIds: [],
                    magazineId: this.$route.query.magazineId,
                    columnId: undefined,
                    columnNum: undefined,
                    contentNum: undefined,
                    introduction: undefined,
                    cover: undefined,
                    trialRead: 1,
                    wordCnt: undefined,
                    picCnt: undefined
    
                },
                formRules: {
                    title: [{
                        required: true,
                        message: '标题不能为空',
                        trigger: 'blur'
                    }],
    
                    magazineId: [{
                        required: true,
                        message: '杂志为必选项',
                        trigger: 'change'
                    }],
                    columnId: [{
                        required: true,
                        message: '杂志栏目为必选项',
                        trigger: 'change'
                    }],
                    contentNum: [{
                        required: true,
                        message: '文章排序不能为空',
                        trigger: 'blur,change'
                    }],
                    cover: [{
                        required: true,
                        message: '封面图必须上传',
                        trigger: 'change'
                    }],
                    content: [{
                        required: true,
                        message: '文章内容不能为空',
                        trigger: 'blur'
                    }]
    
                },
                imgData: {
                    accept: 'image/gif, image/png, image/jpeg',
                },
                levelOne: [],
                listObj: {},
                options: [{
                    value: '0',
                    label: '图文'
                }],
                classifies: [],
                Tags: [],
                columns: [],
                magazines: [{
                    id: this.$route.query.magazineId,
                    name: this.$route.query.period
                }]
            }
        },
        // watch: {
        //     'form.cover': function(val, oldVal) {
        //         if (val !== undefined) {
        //             document.getElementById("upload_control").childNodes[1].style.display = "none";
        //         } else {
        //             document.getElementById("upload_control").childNodes[1].style.display = "block";
        //         }
        //     }
        // },
        created() {
            this.getMagazineTags()
            this.getMagazineClassify()
            const magazineId = this.$route.query.magazineId
            if (magazineId !== undefined) {
                this.getMagazineColumn(magazineId)
            }
            const contentId = this.$route.query.contentId
            if (contentId !== undefined) {
                this.getEditContent(contentId)
            }
        },
        methods: {
            onSubmit() {
                this.$refs.form.validate((valid) => {
                    this.columns.forEach(column => {
                        if(column.id === this.form.columnId){
                            this.form.columnNum = column.columnNum
                        }
                    })
                    if (valid) {
                        this.form.wordCnt = this.$refs.tinyme.getBodyLength()
                        this.form.picCnt = this.$refs.tinyme.getImgNumber()
                        if (this.form.id === undefined || this.form.id === '') {
                            insertMagazineContent(this.form).then(response => {
                                if (response.code === 0) {
                                    this.$message({
                                        type: 'success',
                                        message: response.msg
                                    })
                                    this.back()
                                }
                            })
                        } else {
                            updateMagazineContent(this.form).then(response => {
                                if (response.code === 0) {
                                    this.$message({
                                        type: 'success',
                                        message: response.msg
                                    })
                                    this.back()
                                }
                            })
                        }
                    }
                })
            },
            getEditContent(contentId) {
                getMagazineContentById(contentId).then(response => {
                    if (response.code === 0) {
                        this.form = response.data
                        this.magazines[0] = {
                            id: this.form.magazineId,
                            name: this.$route.query.period
                        }
                        this.getMagazineColumn(this.form.magazineId)
                    }
                })
            },
            successFile(response, file, fileList) {
                if(response.code === 0){
                    this.form.cover = response.data
                }else{
                    this.$message({
                        type: 'error',
                        message: response.msg
                    })
                }
            },
            handleRemove(file, fileList) {
                this.form.cover = undefined
                document.getElementById("upload_control").childNodes[1].style.display = "block";
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            handleBefore(file) {
                const isType = (this.imgData.accept.indexOf(file.type) !== -1)
                // const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isType) {
                    this.$message.error('图片格式不正确');
                }
                // if (!isLt2M) {
                //     this.$message.error('图片不能超过５M');
                // }
                // const isSize = new Promise(function(resolve, reject) {
                //     let _URL = window.URL || window.webkitURL;
                //     let img = new Image()
                //     img.onload = function() {
                //         let valid = (img.width == 315 && img.height == 315)
                //         valid ? resolve() : reject();
                //     }
                //     img.src = _URL.createObjectURL(file)
                // }).then(() => {
                //     return file;
                // }, () => {
                //     this.$message.error('图片像素不正确');
                //     return Promise.reject();
                // });
                // if(isJPG && isLt2M && isSize){
                //     document.getElementById("upload_control").childNodes[1].style.display = "none";
                // }
                return isType
            },
            getMagazineTags() {
                getChildTags().then(response => {
                    if (response.code === 0) {
                        this.Tags = response.data
                    }
                })
            },
            getMagazineClassify() {
                getAllClassifies().then((response) => {
                    if (response.code === 0) {
                        this.classifies = response.data
                    }
                })
            },
            getMagazineColumn(magazineId) {
                const params = {
                    magazineId: magazineId
                }
                getSelectColumnBox(params).then((response) => {
                    if (response.code === 0) {
                        this.columns = response.data
                    }
                })
            },
            getInputLength(input) {
                if (input === undefined) return 0
                const length = input.length
                return length
            },
            back() {
                this.$router.back(-1)
            },
            MessageBox(type, message) {
                this.$message({
                    type: type,
                    message: message
                })
            }
        }
    }
</script>

<style rel="stylesheet/scss" lang="scss">
    .go_back {
        margin: 20px;
    }
    
    .upload_span {
        margin-left: 10px;
        float: left;
        font-size: 16px;
        color: gray;
    }
    
    .free_read_column {
        font-size: 16px;
    }
    
    .el-button--text {
        font-size: 16px;
    }
    
    .online_set {
        margin: 10px;
    }
    
    .form_button {
        width: 120px;
    }
    
    .free_read .el-table__header-wrapper table {
        display: none;
    }
    
    .inline_cloumn_left {
        width: 50%;
        float: left;
    }
    
    .inline_cloumn_right {
        width: 50%;
        float: left;
        position: relative;
        label {
            width: 120px!important;
        }
    }
    
    // .el-textarea{
    //     width: 550px!important;
    // }
</style>
